package com.wjw.redis.stream.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class RedissonConfig {
    @Value("${spring.application.name}")
    private String serverName;

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Value("${spring.redis.database}")
    private int redisDatabase;

    @Value("${spring.redis.password}")
    private String redisPassword;


    @Bean
    public RedissonClient redissonClient() {
        if (!StringUtils.hasText(redisHost) || redisPort <= 0 || redisDatabase < 0 || !StringUtils.hasText(redisPassword)) {
//        if (!StringUtils.hasText(redisHost) || redisPort <= 0 || redisDatabase < 0) {
            throw new IllegalStateException("Redis configuration is not valid");
        }

        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();

        // 验证并设置Redis服务器地址
        String address = "redis://" + redisHost + ":" + redisPort;
        singleServerConfig.setAddress(address);

        // 设置密码和数据库
        singleServerConfig.setPassword(redisPassword);
        singleServerConfig.setKeepAlive(true);
        singleServerConfig.setDatabase(redisDatabase);
        singleServerConfig.setClientName(serverName);

        try {
            return Redisson.create(config);
        } catch (Exception e) {
            // Log the exception or handle it according to your application's policy
            throw new RuntimeException("Failed to create Redisson client", e);
        }
    }
}

